import { observable, action, toJS } from 'mobx';
import { ListViewPage, SearchAdvanced, RouteLayout, SearchPage } from 'weaver-mobile-page';
import * as Api from '../../api';
import { PARAMS } from '../../util';

const initalState = {
  adSearch: null,
  votingList: null,
  path: '',
  page: '',
  AdValue: '',
  fillLayout: null,
  viewLayout: null,
  resultLayout: null,
  searchPageStore: null,
  localeStorageKey: '',
}
const activeArr = [
  {key: 'noparticipating', id: '0'},
  {key: 'join', id: '1'},
  {key: 'call', id: '2'},
  {key: 'relatedme', id: '3'},
]
const template = { default: [{ key: 'col', configs: [{ key: 'col_row', configs: [{ key: 'name' }] }] }] };
export default class VotingStore {
  @observable votingNum = null;
  @observable resultLoading = false;
  @observable noJoinLoading = false;
  @observable votingLoading = false;
  @observable path = initalState.path;
  @observable page = initalState.page;
  @observable AdValue = initalState.AdValue;
  @observable adSearch = initalState.adSearch;
  @observable votingList = initalState.votingList;
  @observable fillLayout = initalState.fillLayout;
  @observable viewLayout = initalState.viewLayout;
  @observable resultLayout = initalState.resultLayout;
  @observable localeStorageKey = initalState.localeStorageKey;
  @observable noJoinList = new ListViewPage.Store({ route: '/voting' }); // 未参与的调查
  @observable newResList = new ListViewPage.Store({ route: '/voting' }); // 调查结果列表
  @observable relatedList = new ListViewPage.Store({ route: '/voting/relatedme' }); // 与我相关的调查
  @observable votingResList = new ListViewPage.Store({ route: '/voting' }); // 首页调查结果列表

  @observable defaultParams = {};

  @action setStoreState = (params) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    })
  }

  @action clear = () => this.setStoreState(initalState);

  /* 首页请求数据 */
  @action myVotingNum = () => {
    Api.myVotingNum().then(res => {
      this.votingNum = res.data;
    })
  }

  @action getList = (params) => {
    this.noJoinLoading = true;
    params = {viewcondition: 0}
    Api.myVoting(params).then(res=>{
      const dataKey = res.sessionkey;
      if (dataKey) {
        this.noJoinList.getData({ dataKey }, () => this.noJoinLoading = false, true);
      }
    })
  }

  @action getNewResult = () => {
    this.resultLoading = true;
    this.newResList.clearData();
    Api.result().then(res => {
      const dataKey = res.sessionkey;
      if (dataKey) {
        this.votingResList.getData({ dataKey, current: 1, pageSize: 5 }, () => this.resultLoading = false, true);
      }
    })
  }

  /* 通用 */
  @action getAdsearchCondition = (params) => {
    this.adSearch && this.adSearch.getData({
      method: 'GET',
      url: '/api/voting/list/condition',
      params: {...PARAMS, ...params}
    }).then((form) => {
      this.defaultParams = form.formParams || {};
    })
  }

  @action updateAdvance = (val) => {
    this.AdValue = val;
    this.adSearch.form.updateField('subject', val);
  }

  @action onSearch = (v) => {
    v && this.updateAdvance(v);
    this.page ? this.getVotingList() : this.getResult();
    if (this.AdValue !== '') {
      let searchHistory = localStorage.getItem(this.localeStorageKey);
      searchHistory = searchHistory ? JSON.parse(searchHistory) : [];
      searchHistory = searchHistory.filter(h => h.key !== this.AdValue);
      searchHistory.unshift({ key: this.AdValue, name: this.AdValue });
      localStorage.setItem(this.localeStorageKey, JSON.stringify(searchHistory));
    }
  }

  @action searchPageClear = () => {
    localStorage.removeItem(this.localeStorageKey);
    this.searchPageStore.list.setState({ data: [] });
  }

  /* 与我相关的调查 && 我参与的调查 */
  @action inital = () => {
    this.localeStorageKey = `searchHistory__${this.page}`;
    this.adSearch = new SearchAdvanced.Store({ route: this.path, id: 'adSearch' });
    this.votingList = new ListViewPage.Store({ route: this.path, id: this.page });
    this.searchPageStore = new SearchPage.Store({ route: this.path, id: 'history', template });
    this.getAdsearchCondition({listType:'myVoting'});
    this.fillLayout = new RouteLayout.Store({ route: this.path, id: 'fill/:id'});
    this.viewLayout = new RouteLayout.Store({ route: this.path, id: 'view/:id'});
    this.resultLayout = new RouteLayout.Store({ route: this.path, id: 'result/:id'});
  }

  @action getParams = (key) => toJS(activeArr).filter(v => v.key === key)[0].id;

  @action getVotingList = () => {
    this.votingLoading = true;
    this.votingList.clearData();
    let formParams = this.adSearch && this.adSearch.form.formParams;
    formParams = formParams || {};
    let params = {
      viewcondition: this.getParams(this.page),
      ...formParams
    }
    Api.myVoting(params).then(res => {
      const dataKey = res.sessionkey;
      if (dataKey) {
        this.votingList.getData({ dataKey }, () => this.votingLoading = false, true);
      }
    })
  }

  @action doVotingReset = () => {
    this.AdValue = '';
    this.adSearch.form.resetFields();
    this.getVotingList();
  }

  /* 调查结果列表 */
  @action getResult = () => {
    this.resultLoading = true;
    this.newResList.clearData();
    let formParams = this.adSearch && this.adSearch.form.formParams;
    formParams = formParams || {};
    Api.result(formParams).then(res => {
      const dataKey = res.sessionkey;
      if (dataKey) {
        this.newResList.getData({ dataKey }, () => this.resultLoading = false, true);
      }
    })
  }
  
  @action resInit = () => {
    this.localeStorageKey = `searchHistory__resultList`;
    this.adSearch = new SearchAdvanced.Store({ route: '/voting/resultList', id: 'adSearch' });
    this.searchPageStore = new SearchPage.Store({ route: '/voting/resultList', id: 'history', template });
    this.getAdsearchCondition({listType:'result'});
  }

  @action doResReset = () => {
    this.AdValue = '';
    this.adSearch.form.resetFields();
    this.getResult();
  }
}